const cp = require('child_process');
const log4js = require('log4js');
const logger = log4js.getLogger('log');


module.exports = {
    async '/show/:name!GET' () {
        const {name} = this.params;
        await this.forward('test', {name});
    },
    async '/tail2/:name!ALL' () {
        try {
            const {name} = this.params;
            const tail = cp.spawn('tail', ['-f', '-n', 50, __dirname+'/../logs/'+name+'.log']);
            this.ctx.status = 200;
            if (!this.ctx.sse) {
                this.ctx.body = 'sse null';
            }
            tail.stdout.on('data', (data) => {
                const str = data + '';
                if (this.ctx.sse) {
                    this.ctx.sse.send(str);
                }
            });
            this.ctx.req.on('close', () => {
                this.ctx.sse.sendEnd('close');
            });
        } catch (e) {
            logger.error(e);
        }
    },
    async '/tail/:name/:lines?!GET' () {
        try {
            const {name, lines} = this.params;
            const tail = cp.spawn('tail', ['-n', lines || 50, __dirname+'/../logs/'+name+'.log']);
            let str = '';
            await new Promise((resolve, reject) => {
                tail.stdout.on('data', (data) => {
                    str += data;
                    resolve();
                });
                
                tail.stderr.on('data', (data) => {
                    str += data;
                    resolve();
                });
                
                tail.on('close', (code) => {
                    str = `子进程退出，退出码 ${code}`;
                    resolve();
                });
                tail.on('error', (err) => {
                    str = err.toString();
                    resolve();
                });
            });
            this.send(str);
        } catch (e) {
            logger.error(e);
            this.ctx.body = e;
        }
    },
}